
#include <vector>
#include <sys/types.h>
#include <sys/socket.h>
#include <functional>

#include "InetAddr.hpp"
#include "Threadpool.hpp"

using task_t = std::function<void()>;

class MessageRoute
{
private:
    bool IsExit(InetAddr addr)
    {
        for (auto a : _online_user)
        {
            if (a == addr)
            {
                return true;
            }
        }
        return false;
    }

public:
    MessageRoute()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }
    void AddUser(InetAddr addr)
    {
        LockGuard lockguard(&_mutex);
        if (IsExit(addr))
            return;
        _online_user.push_back(addr);
    }

    void DelUser(InetAddr addr)
    {
        LockGuard lockguard(&_mutex);
        for(std::vector<InetAddr>::iterator it = _online_user.begin();it != _online_user.end();it++)
        {
            if(*it == addr)
            {
                _online_user.erase(it);
                break;
            }
        }
    }

    void RouteHelper(int sockfd, std::string message, InetAddr who)
    {
        LockGuard lockguard(&_mutex);
        // 2. 进行消息转发
        std::string rsp = "\n[" + who.Ip() +
                          ":" + std::to_string(who.Port()) +
                          "]#" + message + "\n";

        for (auto u : _online_user)
        {
            struct sockaddr_in clientaddr = u.Addr();
            ::sendto(sockfd, rsp.c_str(), rsp.size(), 0, (struct sockaddr *)&clientaddr, sizeof(sockaddr_in));
        }
    }

    void Route(int sockfd, std::string message, InetAddr who)
    {
        // 1.我们任务，首次发送消息，不光光发送消息，还要把插入到在线用户中
        AddUser(who);
        // 1.1 如果客户端要退出
        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
            ::close(sockfd);//既然你退出了，那么还留着sockfd干嘛
            return;
        }
        
        // 2. 构建任务对象，入队列，让线程池进行转发
        task_t t = std::bind(&MessageRoute::RouteHelper,this,sockfd,message,who); 
        ThreadPool<task_t>::GetInstance()->Enqueue(t);
    } 

    ~MessageRoute()
    {
        pthread_mutex_destroy(&_mutex);
    }

private:
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _mutex;
};
